package net.sf.rose.business.action.define;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.rose.business.action.Download;
import net.sf.rose.business.bean.base.DownloadFileBean;
import net.sf.rose.business.bean.database.DataTypeMetaBean;
import net.sf.rose.business.bean.database.DataTypeMetaBeans;
import net.sf.rose.business.service.DBMetaService;
import net.sf.rose.exception.SystemErrorCode;
import net.sf.rose.exception.SystemException;
import net.sf.rose.jdbc.UserBean;
import net.sf.rose.jdbc.service.Service;
import net.sf.rose.web.OnlineUserListener;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

/**
 * 功能：
 * 
 * @author fengjian
 * @since 2014/01/29
 */
@Controller
@RequestMapping("/define/dbmeta")
public class DBMetaController {

	private static String LIST_PAGE = "define/dbmeta/list";
	private static String VIEW_PAGE = "define/dbmeta/edit";

	/**
	 * 普通查询
	 */
	@RequestMapping("/list.html")
	public ModelAndView list(HttpServletRequest request,Service service) {
		Map<String, DataTypeMetaBeans> bean = DBMetaService.getAll();
		ModelAndView mav = new ModelAndView(LIST_PAGE);
		mav.addObject("bean", bean);
		return mav;
	}

	/**
	 * 
	 */
	@RequestMapping("/add.html")
	public ModelAndView add(HttpServletRequest request) {
		DataTypeMetaBeans bean = new DataTypeMetaBeans();
		ModelAndView mav = new ModelAndView(VIEW_PAGE);
		mav.addObject("bean", bean);
		return mav;
	}

	/**
	 * 
	 */
	@RequestMapping("/get.html")
	public ModelAndView get(HttpServletRequest request, String name) {
		DataTypeMetaBeans bean = DBMetaService.getAll().get(name);
		ModelAndView mav = new ModelAndView(VIEW_PAGE);
		mav.addObject("bean", bean);
		return mav;
	}

	/**
	 * 
	 */
	@RequestMapping("/delete.html")
	public ModelAndView delete(HttpServletResponse response, String name) throws Exception {
		DBMetaService.getAll().remove(name);
		response.reset();
		response.setContentType("application/json;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		PrintWriter pw = response.getWriter();
		pw.write("{\"msg\":\"删除成功！\"}");
		pw.flush();
		pw.close();
		return null;
	}

	/**
	 * 提交操作
	 */
	@RequestMapping("/save.html")
	public ModelAndView save(HttpServletRequest request,DataTypeMetaBeans bean) {
		bean.setDataMetas(getFieldBeanList(request));
		DBMetaService.getAll().put(bean.getName(), bean);
		ModelAndView mav = new ModelAndView("ajaxDone");
		mav.addObject("statusCode", 200);
		mav.addObject("message", "操作成功！");
		mav.addObject("callbackType", true);
		return mav;
	}

	private List<DataTypeMetaBean> getFieldBeanList(HttpServletRequest request) {
		List<DataTypeMetaBean> list = new ArrayList<DataTypeMetaBean>();
		int i = 0;
		do {
			// 参数的键值
			String name = request.getParameter("items.name[" + i + "]");
			if (name == null || name.equals("")) {
				break;
			}
			DataTypeMetaBean param = new DataTypeMetaBean();
			param.setName(name);
			// 参数的数据格式
			String dbType = request.getParameter("items.dbType[" + i + "]");
			if (dbType != null && !dbType.equals("")) {
				param.setDbType(dbType);
			}
			// 如果值为空时使用默认值
			String javaType = request.getParameter("items.javaType[" + i + "]");
			if (javaType != null && !javaType.equals("")) {
				param.setJavaType(javaType);
			}
			list.add(param);
			i++;
		} while (i > 0);
		return list;
	}

	/**
	 * 提交操作
	 */
	@RequestMapping("/saveAll.html")
	public ModelAndView saveAll(HttpServletRequest request) {
		UserBean user = OnlineUserListener.getOnlineUser(request);
		DBMetaService.save(user);
		ModelAndView mav = null;
		mav = new ModelAndView("ajaxDone");
		mav.addObject("statusCode", 200);
		mav.addObject("message", "操作成功！");
		mav.addObject("callbackType", true);
		return mav;
	}

	/**
	 * 提交操作
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/input.html")
	public ModelAndView input(HttpServletRequest request) {
		Object obj = request.getSession().getAttribute(Download.TEMP_FILES);
		if (obj == null) {
			throw new SystemException("Session中找不到上传的文件。", SystemErrorCode.PRARAMTER_LOST_ERROR);
		}
		Map<String, DownloadFileBean> map = (Map<String, DownloadFileBean>) obj;
		InputStream in = null;
		try {
			for (DownloadFileBean bean : map.values()) {
				if (bean.getData() != null) {
					in = bean.getData().getInputStream();
				}
			}
		} catch (IOException e) {
			throw new SystemException("上传的文件读取错误 !", SystemErrorCode.PRARAMTER_LOST_ERROR);
		}
		if (in == null) {
			throw new SystemException("没有找到上传的文件 !", SystemErrorCode.PRARAMTER_LOST_ERROR);
		}
		DBMetaService.input(in);
		ModelAndView mav = null;
		mav = new ModelAndView("ajaxDone");
		mav.addObject("statusCode", 200);
		mav.addObject("message", "导入成功！");
		mav.addObject("callbackType", true);
		return mav;
	}

	/**
	 * 提交操作
	 */
	@RequestMapping("/output.html")
	public String output(HttpServletRequest request) {
		File file = DBMetaService.output();
		request.setAttribute(Download.DOWNLOAD_FILE, file);
		request.setAttribute(Download.DOWNLOAD_FILE_NAME, "数据库元数据配置.xml");
		return "forward:/download.html";
	}
}
